package com.zhang.third.day10;

import com.zhang.third.utils.ProductViewCountPerWindow;
import com.zhang.third.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @title: 使用KeyedProcessFunction实现滑动窗口-- 全窗口聚合
 * @author: zhang
 * @date: 2022/4/14 07:55
 */
public class SlidingWindow1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0], arr[1], arr[2], arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .keyBy(r -> r.productId)
                // 使用底层api实现滑动窗口功能，计算商品在每个窗口的pv
                .process(new MySlidingWindow())
                .keyBy(r->r.windowEndTime)
                .process(new TopN(3))
                .print();


        env.execute();
    }
    // 使用底层API实现滑动窗口
    public static class MySlidingWindow extends KeyedProcessFunction<String,UserBehavior,ProductViewCountPerWindow>{
        // 定义窗口长度 1小时
        private long slidingWindowSize = 60 * 60 * 1000L;
        // 定义窗口滑动步长 5分钟
        private long slidingWindowStep = 5 * 60 * 1000L;
        // 定义map状态
        // key ： 窗口的开始时间
        // value：属于窗口所有事件
        private MapState<Long, List<UserBehavior>> mapState;

        @Override
        public void open(Configuration parameters) throws Exception {
            mapState = getRuntimeContext().getMapState(
                    new MapStateDescriptor<Long, List<UserBehavior>>(
                            "map-state",
                            Types.LONG,
                            Types.LIST(Types.POJO(UserBehavior.class))
                    )
            );
        }

        @Override
        public void processElement(UserBehavior value, KeyedProcessFunction<String, UserBehavior, ProductViewCountPerWindow>.Context ctx, Collector<ProductViewCountPerWindow> out) throws Exception {
            // 计算窗口开始时间
            long currTs = value.ts;
            ArrayList<Long> windowStarts = new ArrayList<>((int) (slidingWindowSize / slidingWindowStep));
            // 获取当前事件时间属于的最后一个滑动窗口
            long lastStart = getWindowStart(currTs, slidingWindowStep);
            // 往前依次计算当前事件时间属于的所有滑动窗口
            for (long start = lastStart; start > currTs - slidingWindowSize; start -= slidingWindowStep) {
                windowStarts.add(start);
            }
            // 为事件分配窗口
            for (Long windowStart : windowStarts) {
                if (!mapState.contains(windowStart)) {
                    ArrayList<UserBehavior> events = new ArrayList<>();
                    events.add(value);
                    mapState.put(windowStart, events);
                } else {
                    mapState.get(windowStart).add(value);
                }
                // 注册窗口触发定时器
                ctx.timerService().registerEventTimeTimer(windowStart + slidingWindowSize - 1L);
            }
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<String, UserBehavior, ProductViewCountPerWindow>.OnTimerContext ctx, Collector<ProductViewCountPerWindow> out) throws Exception {
            long windowEnd = timestamp + 1L;
            long windowStart = windowEnd - slidingWindowSize;
            long count = mapState.get(windowStart).size();
            mapState.remove(windowStart);
            out.collect(new ProductViewCountPerWindow(
                    ctx.getCurrentKey(),
                    count,
                    windowStart,
                    windowEnd
            ));
        }
    }

    // 求TopN
    public static class TopN extends KeyedProcessFunction<Long, ProductViewCountPerWindow, String> {
        private int n;
        private ListState<ProductViewCountPerWindow> listState;

        public TopN(int n) {
            this.n = n;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<ProductViewCountPerWindow>(
                            "list", Types.POJO(ProductViewCountPerWindow.class)
                    )
            );
        }

        @Override
        public void processElement(ProductViewCountPerWindow value, KeyedProcessFunction<Long, ProductViewCountPerWindow, String>.Context ctx, Collector<String> out) throws Exception {
            listState.add(value);
            ctx.timerService().registerEventTimeTimer(value.windowEndTime + 1L);
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Long, ProductViewCountPerWindow, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
            ArrayList<ProductViewCountPerWindow> arrayList = new ArrayList<>();
            for (ProductViewCountPerWindow e : listState.get()) {
                arrayList.add(e);
            }
            // 遍历完清空状态，缓解内存压力
            listState.clear();
            // 排序
            arrayList.sort(new Comparator<ProductViewCountPerWindow>() {
                @Override
                public int compare(ProductViewCountPerWindow o1, ProductViewCountPerWindow o2) {
                    return (int) (o2.count - o1.count);
                }
            });

            // 格式化输出字符串
            StringBuilder result = new StringBuilder();
            result.append("=====================================\n");
            result.append("窗口结束时间：" + new Timestamp(ctx.getCurrentKey()) + "\n");
            for (int i = 0; i < n; i++) {
                ProductViewCountPerWindow tmp = arrayList.get(i);
                result.append("NO." + (i + 1) + ".商品ID是：" + tmp.productId + ",浏览次数是：" + tmp.count + "\n");
            }
            result.append("=====================================\n");
            out.collect(result.toString());
        }
    }

    // 计算窗口开始时间

    /**
     * @param timestamp 当前事件时间
     * @param windowStep 滑动窗口步长
     * @return 属于滑动窗口的最后一个开始时间
     */
    public static long getWindowStart(long timestamp, long windowStep) {
        return timestamp - (timestamp + windowStep) % windowStep;
    }
}
